package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 图片上传业务实现
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1 参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确文件");
        }
        // 当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();// 2 上传到oss
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        String filename = multipartFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (!checkSuffix(suffix)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文件格式不支持");
        }
        // 2 上传到oss 得到路径
        //上传的文件路径
        String filenameAll = UUID.randomUUID().toString().replaceAll("-", "");
        try {
            filenameAll = fileStorageService.store(prefix, filenameAll + suffix, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败" + e.getMessage());
        }
        //创建素材对象  存入素材表
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(filenameAll);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //返回数据  data: 返回素材对象  将图片路径补全
        wmMaterial.setUrl(webSite + filenameAll);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材图片查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //参数检查
        dto.checkParam();
        //执行查询
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery();
        //收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());
        //按时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //分页
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage = page(pageParam, wrapper);
        List<WmMaterial> records = resultPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        //结果封装
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal());
        pageResponseResult.setData(records);
        return pageResponseResult;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        //数据检测
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请传入正确的素材id");
        }
        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "素材已被引用");
        }
        // 删除素材库
        removeById(id);
        //删除oss
        fileStorageService.delete(wmMaterial.getUrl());
        //封装结果
        return ResponseResult.okResult();
    }

    /**
     * 收藏与取消收藏素材
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请发送正确的id");
        }
        //2.更新状态
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材不存在");
        }
        //获取当前用户信息  判断是否是当前用户上传的素材
        Integer userId = WmThreadLocalUtils.getUser().getId();
        if(!userId.equals(wmMaterial.getUserId())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"只能收藏自己上传的素材");
        }
        //更新状态
        wmMaterial.setIsCollection(type);
        updateById(wmMaterial);
        return ResponseResult.okResult();
    }

    //判断图片后缀名是否符合要求
    private boolean checkSuffix(String suffix) {
        if (StringUtils.isBlank(suffix)) {
            return false;
        }
        List<String> list = Arrays.asList(".jpg", ".png", ".gif", ".jpeg");
        boolean isAllow = false;

        for (String allowSuffix : list) {
            if (suffix.equals(allowSuffix)) {
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }
}
